// 1. 定义全局变量
let localStream;
let peerConnection;
const signalingServer = new WebSocket('ws://localhost:8080'); // 信令服务器

// 2. 初始化：获取本地媒体流
async function init() {
    try {
        // 请求摄像头和麦克风权限
        localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        document.getElementById('localVideo').srcObject = localStream;
    } catch (err) {
        console.error("获取媒体设备失败:", err);
    }
}

// 3. 创建RTCPeerConnection并设置ICE候选
function createPeerConnection() {
    // 配置STUN服务器（Google公共测试服务器）
    const configuration = {
        iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
    };
    peerConnection = new RTCPeerConnection(configuration);

    // 添加本地媒体流到连接中
    localStream.getTracks().forEach(track => {
        peerConnection.addTrack(track, localStream);
    });

    // 监听远程媒体流
    peerConnection.ontrack = (event) => {
        document.getElementById('remoteVideo').srcObject = event.streams[0];
    };

    // 监听ICE候选（网络穿透信息）
    peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            // 通过信令服务器发送ICE候选给对方
            signalingServer.send(JSON.stringify({
                type: 'ice-candidate',
                candidate: event.candidate
            }));
        }
    };
}

// 4. 发起通话（创建Offer）
async function startCall() {
    createPeerConnection();
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);

    // 通过信令服务器发送Offer
    signalingServer.send(JSON.stringify({
        type: 'offer',
        offer: offer
    }));
}

// 5. 处理信令服务器消息
signalingServer.onmessage = async (message) => {
    const data = JSON.parse(message.data);
    if (!peerConnection) createPeerConnection();

    switch (data.type) {
        case 'offer':
            // 收到Offer，设置远程描述并生成Answer
            await peerConnection.setRemoteDescription(data.offer);
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            signalingServer.send(JSON.stringify({
                type: 'answer',
                answer: answer
            }));
            break;

        case 'answer':
            // 收到Answer，设置远程描述
            await peerConnection.setRemoteDescription(data.answer);
            break;

        case 'ice-candidate':
            // 添加对方的ICE候选
            await peerConnection.addIceCandidate(data.candidate);
            break;
    }
};

// 初始化页面
init();